<template>
  <div id="app">
    <!-- 面包屑 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/">活动管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 面板 -->
    <el-card class="box-card">
      <el-row>
        <el-col :span="20">
          <div class="grid-content bg-purple">
            <el-input
              v-model="queryInfo.query"
              clearable
              @clear="getUserList"
              placeholder="请输入内容"
              class="input-with-select"
            >
              <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple-light">
            <el-row>
              <el-button type="info" round @click="dialogVisible=true">发展下线</el-button>
            </el-row>
          </div>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table border :data="userlist" stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column fixed prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="kaiguan(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-row>
              <!-- 编辑按钮 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="showEditUser(scope.row.id)"
              ></el-button>
              <!-- 分配按钮   -->
              <el-button
                @click="showRoleDialog(scope.row)"
                type="warning"
                icon="el-icon-setting"
                circle
              ></el-button>
              <!-- 删除按钮 -->
              <el-button
                @click="removeUser(scope.row.id)"
                type="danger"
                icon="el-icon-delete"
                circle
              ></el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="400"
      ></el-pagination>
    </el-card>

    <!-- 对话框 -->
    <el-dialog @close="closeAddDialog" title="添加用户" :visible.sync="dialogVisible" width="50%">
      <span>
        <!-- 表单 -->
        <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRules">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色框 -->
    <el-dialog title="提示" :visible.sync="userDialogVisible" width="50%">
      <div>姓名:{{userinfo.username}}</div>
      <div>角色名称:{{userinfo.role_name}}</div>
      <!-- 角色下拉框 -->
      <el-select v-model="selectedRoleId" placeholder="请选择">
        <el-option v-for="item in rolelist" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
      </el-select>

      <span slot="footer" class="dialog-footer">
        <el-button @click="userDialogVisible">取 消</el-button>
        <el-button @click="addRole" type="primary">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改用户" :visible.sync="EditdialogVisible" width="50%">
      <el-form ref="form" :model="editForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <!-- <el-form-item label="密码">
            <el-input v-model="editForm.password"></el-input>
        </el-form-item>-->
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">修 改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkEmail = (rule, value, cb) => {
      var regEmail = /^\w+@\w+\.\w+$/;
      if (!regEmail.test(value)) return cb(new Error("邮箱格式不正确"));
      return cb();
    };
    var checkMobile = (rule, value, cb) => {
      var regMobile = /^1\d{10}$/;
      if (!regMobile.test(value)) return cb(new Error("电话格式不正确"));
      return cb();
    };
    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2
      },
      userlist: [],
      total: 0,
      dialogVisible: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度3-10位", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输密码", trigger: "blur" },
          { min: 3, max: 10, message: "长度3-10位", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      editForm: {},
      EditdialogVisible: false,
      userDialogVisible: false,
      userinfo: {},
      rolelist: [],
      selectedRoleId: "",

    };
  },
  created() {
    this.getUserList();
  },

  methods: {
    async addRole(){
      // console.log(this.selectedRoleId);
      if(!this.selectedRoleId){
        return this.$message.error("请选择角色")
      }
      const {data:res}=await this.$http.put(`users/${this.userinfo.id}/role`,{
        rid:this.selectedRoleId
      })
       if(res.meta.status!=200){
         return this.$message.error("分配角色失败")

       }
       this.$message.success("分配角色成功")
       this.getUserList();
       this.userDialogVisible=false
    },
    async showRoleDialog(userinfo) {
      this.userinfo = userinfo;
      let { data: res } = await this.$http.get("roles");
      if (res.meta.status != 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.rolelist = res.data;
      this.userDialogVisible = true;
    },
    async removeUser(id) {
      let result = await this.$confirm(
        "此操作将永久删除用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (result !== "confirm") return this.$message.info("取消删除");
      let { data: res } = await this.$http.delete("users/" + id);
      if (res.meta.status != 200) return this.$message.error("删除失败");
      this.$message.success("删除成功");
      this.getUserList();
    },

    async showEditUser(id) {
      let { data: res } = await this.$http.get("users/" + id);
      console.log(res);
      this.editForm = res.data;
      this.EditdialogVisible = true;
    },
    async editUser() {
      let { data: res } = await this.$http.put("users/" + this.editForm.id, {
        email: this.editForm.email,
        mobile: this.editForm.mobile,
        username: this.editForm.mobile
      });
      console.log(res);
      if (res.meta.status != 200) return this.$message.error("修改失败");
      this.$message.success("修改成功");
      this.getUserList();
      this.EditdialogVisible = false;
    },
    // 添加用户
    addUser() {
      // 预验证
      this.$refs.addFormRef.validate(async valid => {
        console.log(valid);
        if (!valid) return;
        let { data: res } = await this.$http.post("users", this.addForm);
        if (res.meta.status != 201) return this.$message.error("添加失败");
        this.$message.success("添加成功");
        this.getUserList();
        this.dialogVisible = false;
      });
    },
    closeAddDialog() {
      console.log("关闭");
      this.$refs.addFormRef.resetFields();
    },
    // 用户列表
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      if (res.meta.status != 200) return this.$message.error("获取失败");
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },

    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    // 状态开关
    async kaiguan(userinfo) {
      console.log(userinfo);
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;

        return this.$message.error("更新状态失败");
      }
      this.$message.success("更新状态成功");
    }
  }
};
</script>

<style>
.box-card {
  margin-top: 15px;
}
</style>
 